//
//  GFBaseNetWork.m
//  MYLC
//
//  Created by lixiao on 2016/11/2.
//  Copyright © 2016年 MR.S. All rights reserved.
//

#import "GFBaseNetWork.h"
#import <AFNetworking/AFNetworking.h>
#import <objc/runtime.h>
#import "GFUploadImgNetWork.h"

// 系统版本号
#define kSystemVersion [[UIDevice currentDevice] systemVersion]

static char requestURL;
static char requestMethod;
static char requestDict;
static char cachetime;
static char imageData;


@implementation GFBaseNetWork {

    HostStatusStyles currentHostType;
    NSString *currentUrl;
}

#pragma mark -
#pragma mark - 网络请求

#pragma mark--普通请求

+ (GFBaseNetWork *)requestURL:(NSString*)url
                 hostType:(HostStatusStyles)hostType
                   parmas:(NSDictionary*)dic
       cacheTimeInSeconds:(NSInteger)cacheTime
           requestSuccess:(SucessBlock)sucessBlock
            requestFailed:(FailedBlock)failedBlock {
    
    GFBaseNetWork *netWork = [[self alloc] initWithRequestUrl:url hostType:hostType parmas:dic cacheTime:cacheTime];
    
    [netWork startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
      
     // 输出请求信息
    [netWork showLogRequestNetWork:netWork requestObject:request];
    [netWork dealSuccessResponseWithhostType:hostType url:url request:request requestSuccess:sucessBlock requestFailed:failedBlock];
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
        // 输出请求信息
        [netWork showLogRequestNetWork:netWork requestObject:request];
        [netWork dealFailResponseWithhostType:hostType url:url request:request requestSuccess:sucessBlock requestFailed:failedBlock];
    }];
    
    return netWork;
}

#pragma mark--普通缓存请求

+ (GFBaseNetWork *)requestFromCacheURL:(NSString *)url
                          hostType:(HostStatusStyles)hostType
                            parmas:(NSDictionary *)dic
                    requestSuccess:(SucessBlock)sucessBlock
                     requestFailed:(FailedBlock)failedBlock {
    
    GFBaseNetWork *netWork = [[self alloc] initWithRequestUrl:url hostType:hostType parmas:dic cacheTime:1000];
    
    netWork.ignoreCache = YES;
    
    if ([netWork respondsToSelector:NSSelectorFromString(@"loadCacheData")]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        if ([netWork performSelector:NSSelectorFromString(@"loadCacheData")])
#pragma clang diagnostic pop
        {
            !sucessBlock?:sucessBlock(netWork.responseJSONObject);
        }
    }
    [netWork startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        
        // 输出请求信息
        [netWork showLogRequestNetWork:netWork requestObject:request];
        [netWork dealSuccessResponseWithhostType:hostType url:url request:request requestSuccess:sucessBlock requestFailed:failedBlock];
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
        // 输出请求信息
        [netWork showLogRequestNetWork:netWork requestObject:request];
        [netWork dealFailResponseWithhostType:hostType url:url request:request requestSuccess:sucessBlock requestFailed:failedBlock];
    }];
    
    return netWork;
}

#pragma mark--普通Toast请求

+ (GFBaseNetWork *)requestURLWithToast:(NSString*)url
                                hostType:(HostStatusStyles)hostType
                                  parmas:(NSDictionary*)dic
                      cacheTimeInSeconds:(NSInteger)cacheTime
                               needToast:(BOOL)needToast
                    requestSuccess:(SucessBlock)sucessBlock
                     requestFailed:(FailedBlock)failedBlock {
    GFBaseNetWork *netWork = [[self alloc]initWithRequestUrl:url hostType:hostType  parmas:dic cacheTime:cacheTime];
    
    [netWork startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
      
        // 输出请求信息
        [netWork showLogRequestNetWork:netWork requestObject:request];
        id result = request.responseJSONObject;
        NSLog(@"result:%@",result);
        !sucessBlock?:sucessBlock(result);
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
        // 输出请求信息
        [netWork showLogRequestNetWork:netWork requestObject:request];
        [netWork dealFailResponseWithhostType:hostType url:url request:request requestSuccess:sucessBlock requestFailed:failedBlock];

    }];
    
    return netWork;
}
- (AFConstructingBlock)constructingBodyBlock {
    
    AFConstructingBlock block = objc_getAssociatedObject(self, &imageData);
    if (block) {
        return block;
    }else {
        return [super constructingBodyBlock];
    }
}

#pragma mark--图片上传请求
+ (GFBaseNetWork *)uploadImage:(NSString *)url
                        hostType:(HostStatusStyles)hostType
                         paramas:(NSDictionary *)dic
                           image:(UIImage *)image
             requestSuccess:(SucessBlock)sucessBlock
               requestFailed:(FailedBlock)failedBlock {
    
    GFBaseNetWork *netWork = [[self alloc]initWithRequestUrl:url hostType:hostType parmas:dic cacheTime:-1];

    
    
    void (^AFConstructingDataBlock)(id<AFMultipartFormData> formData) = ^(id<AFMultipartFormData> formData) {
        NSData *data = UIImageJPEGRepresentation(image, 0.9);
        NSString *name = @"image";
        NSString *formKey = @"image";
        NSString *type = @"image/jpeg";
        [formData appendPartWithFileData:data name:formKey fileName:name mimeType:type];
    };
    
    
    // 类方法跟示例方法 设置runtime 属性的时候 加以区分 。
     objc_setAssociatedObject(netWork, &imageData,AFConstructingDataBlock ,OBJC_ASSOCIATION_COPY_NONATOMIC);

     [netWork startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
         
         // 输出请求信息
         [netWork showLogRequestNetWork:netWork requestObject:request];
         [netWork dealSuccessResponseWithhostType:hostType url:url request:request requestSuccess:sucessBlock requestFailed:failedBlock];
         
     } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
         
         // 输出请求信息
         [netWork showLogRequestNetWork:netWork requestObject:request];
         [netWork dealFailResponseWithhostType:hostType url:url request:request requestSuccess:sucessBlock requestFailed:failedBlock];
     }];
    
    return netWork;
}

-(void)setSudsUpLoadMethod {
    
//    
//    GFUploadImgNetWork *netWork = [[GFUploadImgNetWork alloc] initWithRequestUrl:url hostType:hostType  parmas:dic cacheTime:-1];
//    [netWork uploadImage:image];
//    
//    
//    [netWork startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
//        
//        // 输出请求信息
//        [netWork showLogRequestNetWork:netWork requestObject:request];
//        [netWork dealSuccessResponseWithhostType:hostType url:url request:request requestSuccess:sucessBlock requestFailed:failedBlock];
//        
//    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
//        
//        // 输出请求信息
//        [netWork showLogRequestNetWork:netWork requestObject:request];
//        [netWork dealFailResponseWithhostType:hostType url:url request:request requestSuccess:sucessBlock requestFailed:failedBlock];
//    }];

}


#pragma mark -
#pragma mark - 处理返回结果 成功/失败  -- 输出Log

#pragma mark -- 处理请求成功
- (void)dealSuccessResponseWithhostType:(HostStatusStyles)hostType
                                    url:(NSString *)url
                                request:(YTKBaseRequest *)request
                         requestSuccess:(SucessBlock)sucessBlock
                          requestFailed:(FailedBlock)failedBlock {
    
    !sucessBlock?:sucessBlock(@"成功");
    
}
#pragma mark -- 处理请求失败
- (void)dealFailResponseWithhostType:(HostStatusStyles)hostType
                                 url:(NSString *)url
                             request:(YTKBaseRequest *)request
                      requestSuccess:(SucessBlock)sucessBlock
                       requestFailed:(FailedBlock)failedBlock {
    
    !failedBlock?:failedBlock(@"失败");
    
}
#pragma mark -- 网络数据输出
-(void)showLogRequestNetWork:(YTKRequest *)netWork
               requestObject:(YTKBaseRequest *)request {

    NSLog(@"header = %@\n request-description = %@\n result:%@",netWork.requestHeaderFieldValueDictionary,netWork,request.responseJSONObject);
}

#pragma mark -
#pragma mark - 网络请求 子类重写方法

- (instancetype)initWithRequestUrl:(NSString *)url hostType:(HostStatusStyles)hostType parmas:(NSDictionary *)dic cacheTime:(NSInteger)cacheTimeInSeconds {
    self = [super init];
    if (self) {
        //确定Host
        currentHostType = hostType;
        currentUrl = url;
        
        // 如果是完整URL 请求 不处理
        if ([url containsString:@"http"] || [url containsString:@"https"]  ) {
        
             objc_setAssociatedObject(self, &requestURL, url, OBJC_ASSOCIATION_COPY_NONATOMIC);
             objc_setAssociatedObject(self, &requestDict,dic, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }else {
    
            NSArray * arr_url = [url componentsSeparatedByString:@":"];
            objc_setAssociatedObject(self, &requestURL, arr_url[1], OBJC_ASSOCIATION_COPY_NONATOMIC);
            objc_setAssociatedObject(self, &requestDict,dic, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            
            if (cacheTimeInSeconds <= 0) {
                cacheTimeInSeconds = -1;
            }
            objc_setAssociatedObject(self, &cachetime,[NSNumber numberWithInteger:cacheTimeInSeconds], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            
            if ([arr_url[0]isEqualToString:@"GET"]) {
                objc_setAssociatedObject(self, &requestMethod, @(0), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            }else if ([arr_url[0] isEqualToString:@"POST"]){
                objc_setAssociatedObject(self, &requestMethod, @(1), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            }
        
        }
        
    }
     return self;
}

- (NSString *)requestUrl {
    return objc_getAssociatedObject(self, &requestURL);
}

- (NSTimeInterval)requestTimeoutInterval {
    return 10;
}

- (NSInteger)cacheTimeInSeconds {
    NSNumber *cacheTime = objc_getAssociatedObject(self, &cachetime);
    return [cacheTime integerValue];
}

- (YTKRequestMethod)requestMethod {
    NSNumber *method = objc_getAssociatedObject(self, &requestMethod);
    return [method integerValue];
}

- (id)requestArgument {
    return objc_getAssociatedObject(self, &requestDict);
}

// 添加header
- (NSDictionary *)requestHeaderFieldValueDictionary{
    
    NSMutableDictionary *headDict = [[NSMutableDictionary alloc] init];

    if (currentHostType == HostTypeStyle1) {
        
        [headDict setObject:@"HostTypeStyle1" forKey:@"Cookie"];
        return headDict;
    }else if (currentHostType == HostTypeStyle2){
        [headDict setObject:@"HostTypeStyle2" forKey:@"Cookie"];
        return headDict;
    }else if (currentHostType == HostTypeStyle3) {
        [headDict setObject:@"HostTypeStyle3" forKey:@"Cookie"];
        return headDict;
    }else {
        return nil;
    }
}

- (NSString *)baseUrl{
    
    if (currentHostType == HostTypeStyle1) {
        return @"www.baidu.com";
    }else if (currentHostType == HostTypeStyle2){
        return @"www.baidu.com";
    }else if (currentHostType == HostTypeStyle3) {
        return @"www.baidu.com";
    }else {
        return nil;
    }

}
@end
